package com.generic;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RegisteredFactories {

	public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(Part.createRandom());
        }
    }

}

interface Factory<T> {
	T create();
}


class Filter extends Part {}

class FuelFilter extends Filter {
    public static class FactoryInner implements Factory<FuelFilter> {
        public FuelFilter create() {
            return new FuelFilter();
        }
    }
}

class AirFilter extends Filter {
    public static class FactoryInner implements Factory<AirFilter> {
        public AirFilter create() {
            return new AirFilter();
        }
    }
}


class Belt extends Part {}

class FanBelt extends Belt {
    public static class FactoryInner implements Factory<FanBelt> {
        public FanBelt create() {
            return new FanBelt();
        }
    }
}

class GeneratorBelt extends Belt {
    public static class FactoryInner implements Factory<GeneratorBelt> {
        public GeneratorBelt create() {
            return new GeneratorBelt();
        }
    }
}

/**Part类的实现如下，注意我们上面的实体类都是Part类的间接子类。在Part类我们注册了我们上面的声明的实体类。所以以后我们如果要创建相关的实体类的话，只需要在调用Part类的相关方法了。这么做的一个好处就是如果的业务中出现了CabinAirFilter或者PowerSteeringBelt的话，我们不需要修改太多的代码，只需要在Part类中将它们注册即可。
 * @author DELL
 *
 */
class Part {
    static List<Factory<? extends Part>> partFactories = new ArrayList<Factory<? extends Part>>();
    static {
        partFactories.add(new FuelFilter.FactoryInner());
        partFactories.add(new AirFilter.FactoryInner());
        partFactories.add(new FanBelt.FactoryInner());
    }

    private static Random rand = new Random(47);

    public static Part createRandom() {
        int n = rand.nextInt(partFactories.size());
        return partFactories.get(n).create();
    }

    public String toString() {
        return getClass().getSimpleName();
    }

}

